﻿using System.IO;
using System.ServiceModel.Channels;
using System.Xml;

namespace RockBus.ServiceModel
{
    public class ResponseFactory
    {
        private const int DefaultMaxHeaderSize = 2048;
        private const string faultActionFormat = "{0}Fault";
        private const string replyActionFormat = "{0}Response";
        private const string responseElementFormat = "<{0}Response xmlns=\"{1}\" />";

        public MessageBuffer CreateResponseBuffer(MessageBuffer requestBuffer)
        {
            using (Message request = requestBuffer.CreateMessage())
            {
                return this.CreateResponseBuffer(request);
            }
        }

        public MessageBuffer CreateResponseBuffer(Message request)
        {
            string replyAction = string.Format(replyActionFormat, request.Headers.Action);
            string responseXml = null;
            using (XmlReader reader = request.GetReaderAtBodyContents())
            {
                string requestElement = reader.LocalName;
                responseXml = string.Format(responseElementFormat,
                    requestElement,
                    reader.NamespaceURI);
            }

            using (StringReader sr = new StringReader(responseXml))
            using (XmlReader xr = XmlReader.Create(sr))
            {
                Message response = Message.CreateMessage(request.Version, replyAction, xr);
                return response.CreateBufferedCopy(responseXml.Length + DefaultMaxHeaderSize);
            }
        }

        public string GetDefaultFaultAction(Message request)
        {
            return string.Format(faultActionFormat, request.Headers.Action);
        }
    }
}